﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Linq.Utils;
using System.Linq.Dynamic;

namespace MyForum.Business.Controllers
{
    public class ForumController : GenericController<Forum, MyForumDataContext>
    {
        public static IQueryable GetAvailableForumFromSection(int sectionId)
        {
            var results = from f in DataContext.Forums
                          where f.SectionId == sectionId
                          let lastMessage = f.Messages.OrderByDescending(m => m.CreationDate).ThenBy(m => m.Id).FirstOrDefault()
                          select new
                          {
                              f.Id,
                              f.Name,
                              NumberOfTopic = f.Messages.Where(m => m.Topic == null).Count(),
                              NumberOfMessage = f.Messages.Count(),
                              LastMessageDate = (DateTime?)lastMessage.CreationDate,
                              LastMessageTitle = lastMessage.Title
                          };
            
            return results;
        }

        public static IQueryable GetAvailableForumFromSection(int sectionId, string sortExpression)
        {
            if (String.IsNullOrEmpty(sortExpression))
            {
                return GetAvailableForumFromSection(sectionId);
            }

            return GetAvailableForumFromSection(sectionId).OrderBy(sortExpression);
        }
    }
}
